using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ClientAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TokenController : ControllerBase
    {
        [Authorize]
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new ContentResult() { Content = "ok" };
        }

        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            return id + "value";
        }

        /// <summary>
        /// 获取token -- 客户端模式
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetToken_Client")]
        public async Task<string> GetToken_Client()
        {
            var client = new HttpClient();
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = "http://localhost:8888/connect/token",
                ClientId = "client",
                ClientSecret = "2691894",
                Scope = "scope1",
            });

            if (tokenResponse.IsError)
            {
                return tokenResponse.Error;
            }

            return tokenResponse.AccessToken;
        }

        /// <summary>
        /// 获取token -- 密码模式
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetToken_Password")]
        public async Task<string> GetToken_Password()
        {
            var client = new HttpClient();
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = "http://localhost:8888/connect/token",
                ClientId = "client",
                ClientSecret = "2691894",
                Scope = "scope1",
                UserName = "test",
                Password = "123456",
            });

            if (tokenResponse.IsError)
            {
                return tokenResponse.Error;
            }

            return tokenResponse.AccessToken;
        }
    }
}